package com.db;

import java.sql.*;

public class MysqlConnect {
//	private String dbName = "/sale-off?useUnicode=true&characterEncoding=utf-8";
//	private String url = "jdbc:mysql://localhost:3306";
//	private String driver = "com.mysql.jdbc.Driver";
//	private String userName = "root";
//	private String password = "root";
	
//	public Statement createConnectDatabase(){
//		Statement db = null;
//		try {
//			//create driver - ALTER TO SUIT YOUR DRIVER/ DBMS
//			Class.forName(driver).newInstance();
//			//create the connection
//			Connection  conn = DriverManager.getConnection(url+dbName,userName,password);			
//			//create statement handle for executing queries
//			db = conn.createStatement();
//			//String vc_sql="SET NAMES 'utf8'";
//			//db.executeQuery(vc_sql);
//			//Statement statement = connection.createStatement(); 
//			
//		} catch (Exception e) {
//			System.out.println(e.toString());
//			return null;
//		}
//		return db;
//	}
	
	public Connection getConnection() throws Exception {
	    try {
	    	String driver = "org.gjt.mm.mysql.Driver";
		    String url = "jdbc:mysql://localhost:3306/sale-off?useUnicode=true&characterEncoding=utf-8";
		    String username = "root";
		    String password = "root";

		    Class.forName(driver);
		    Connection conn = DriverManager.getConnection(url, username, password);
		    return conn;
		} catch (Exception e) {
			 System.err.println("Cannot connect data: " + e.getMessage());
			 return null;
		}
	  }
	
	
	public static void main(String[] args) {
		try {
			int id = 5;	 
			MysqlConnect mysql = new MysqlConnect();
		    PreparedStatement pstmt = null;
		    Connection conn = null;
		    try {
		      conn = mysql.getConnection();
		      conn.setAutoCommit(false);
		      pstmt = conn.prepareStatement("insert into test(id, name) values (?, ?)");
		      pstmt.setInt(1, id);
		      pstmt.setString(2, "tru\"on'ghm Hoàng");
		      pstmt.executeUpdate();
		      conn.commit();
		    } catch (Exception e) {
		      System.err.println("Cannot connect data: " + e.getMessage());
		      e.printStackTrace();	      
		    } finally {
		      pstmt.close();
		      conn.close();
		    }
		} catch (Exception e) {
			System.out.println(e.toString());
		}			
	}
}
